package lucene.server.web.controller.admin;


import lombok.extern.slf4j.Slf4j;
import lucene.server.common.utils.StringUtil;
import lucene.server.database.pool.PoolManager;
import lucene.server.web.dao.DynamicDataSource;
import lucene.server.web.dao.IndexConfigDao;
import lucene.server.web.dao.SystemDao;
import lucene.server.web.model.ConnConfig;
import lucene.server.common.model.Result;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.UUID;


@RestController
@RequestMapping("/admin/conn")
@Slf4j
public class ConnController {

    @GetMapping(value = "/get")
    public Result<?> getConn(HttpServletRequest req) throws SQLException {
        return  Result.OK( SystemDao.getAll("conn", ConnConfig.class));
    }
    @GetMapping(value = "/getPool")
    public Result<?> getPool(HttpServletRequest req) throws SQLException {
        return  Result.OK(PoolManager.getPoolInfo());
    }
    @PostMapping(value = "/update")
    public Result<?> updateConn(@RequestBody ConnConfig conn, HttpServletRequest req) throws SQLException {

        //如果id没有，先判断是否存在
        if (StringUtil.isEmpty(conn.getId()) && SystemDao.checkExists(conn, "connName")) {
            return Result.error("索引名称已存在");
        }
        //新的连接
        if (StringUtil.isEmpty(conn.getId())){
            conn.setId( UUID.randomUUID().toString().replace("-", ""));
        }else{
        //老的连接
            DynamicDataSource.removeDataSourceById(conn.getId());
        }
        String error = checkConn(conn);
        if (!StringUtil.isEmpty(error)){
            return Result.error(error);
        }
        SystemDao.insertOrUpdate(conn);
        DynamicDataSource.createPool(conn);

        return Result.OK();
    }

    @PostMapping(value = "/delete")
    public Result<?> deleteConn(@RequestBody ConnConfig conn, HttpServletRequest req) {
        if(IndexConfigDao.countByCon(conn.getConnName())>0L){
            return Result.error("该连接下存在索引，请先删除索引");
        }
        SystemDao.delete(conn);
        PoolManager.removeConnection(conn.getConnName());
        return Result.OK();
    }
    private String checkConn(ConnConfig connConfig){
        String error = "";
        error += StringUtil.assertNull(connConfig.getConnName(),"名称不能为空\n");
        error += StringUtil.assertNull(connConfig.getConnDriver(),"驱动不能为空\n");
        error += StringUtil.assertNull(connConfig.getConnUrl(),"连接字符串不能为空\n");
        error += StringUtil.assertNull(connConfig.getConnType(),"类型不能为空\n");
        return error;
    }

}

